<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h3 id="hMyname">{myname}</h3>

    <script>
        const data = {
            listeners: new Set(),
            register(listener) {
                this.listeners.add(listener)
                // console.log(listener,"has been registered to",this);
            },
            unregister(listener) {
                this.listeners.delete(listener)
            }
        }

        /* 在data身上定义一个属性 在其变化时能够监听到 */
        Object.defineProperty(data, "myname", {
            // writable:true,
            // enumerable:true,
            // configurable:true,

            get() {
                console.log("getter",this===data);
                return this.stored_name
            },

            set(newValue) {
                console.log("setter",newValue);
                
                this.stored_name = newValue
                this.listeners.forEach(
                    lis => {
                        lis.innerText = newValue
                        // console.log(lis,"'s innerText has changed to",newValue);
                    }
                )
            }
        })
    </script>

    <script>
        data.register(hMyname)

        data.myname = "黑哥"
        console.log("data.myname=",data.myname);

        setTimeout(() => {
            data.myname = "白鸽"
            // console.log("myname changed!");
        }, 5000);
    </script>
</body>

</html>